﻿using AutoMapper;
using MediatR;
using MyRabbit.Application.Command.SlaughteCommand;
using MyRabbit.Application.ErrorCode;
using MyRabbit.Domain;
using MyRabbit.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;

namespace MyRabbit.Application.CommandHandler.SlaughteCommandHandler
{
    public class SlaughteAddCommandHandler : IRequestHandler<SlaughteAddCommand, APIResult<object>>
    {
        /// <summary>
        /// 屠宰仓储
        /// </summary>
        private readonly IRepository<Slaughte> slaughteRep;
        /// <summary>
        /// 产品仓储
        /// </summary>
        private readonly IRepository<Product> proRep;

        /// <summary>
        /// 映射
        /// </summary>
        private readonly IMapper mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="slaughteRep"></param>
        /// <param name="proRep"></param>
        /// <param name="mapper"></param>
        public SlaughteAddCommandHandler(IRepository<Slaughte> slaughteRep, IRepository<Product> proRep, IMapper mapper)
        {
            this.slaughteRep = slaughteRep;
            this.proRep = proRep;
            this.mapper = mapper;
        }

        public async Task<APIResult<object>> Handle(SlaughteAddCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            result.Code = Codes.添加成功;
            result.Message = Codes.添加成功.ToString();

            using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    //添加品种
                    Slaughte breed = mapper.Map<Slaughte>(request);
                    breed.CreateTime = DateTime.Now;

                    await slaughteRep.InsertAsync(breed);

                    //修改产品品种
                    var data = await proRep.GetByIdAsync(request.ProductId);
                    data.SlaughteId = breed.SlaughteId;
                    await proRep.UpdateAsync(data);

                    //提交事务
                    scope.Complete();
                }
                catch (Exception ex)
                {
                    result.Code = Codes.添加失败;
                    result.Message = Codes.添加失败 + ex.Message;
                }




                return await Task.FromResult(result);
            }
        }
    }
}
